<template>
  <div class="organization-selector">
    <el-form-item label="所属总部" v-if="headquartersList.length > 0">
      <el-select
        v-model="internalValue.headquartersId"
        clearable
        placeholder="所属总部"
        style="width: 220px"
        @change="handleHeadquartersChange"
      >
        <el-option
          v-for="item in headquartersList"
          :key="item.organizationId"
          :label="item.organizationName"
          :value="item.organizationId"
        />
      </el-select>
    </el-form-item>

    <el-form-item label="所属连锁" v-if="userType == 4 || internalValue.headquartersId">
      <el-select
        v-model="internalValue.chainId"
        clearable
        placeholder="所属连锁"
        style="width: 220px"
        @change="handleChainChange"
      >
        <el-option
          v-for="item in chainList"
          :key="item.organizationId"
          :label="item.organizationName"
          :value="item.organizationId"
        />
      </el-select>
    </el-form-item>

    <el-form-item label="所属门店">
      <el-select
        v-model="internalValue.storeId"
        clearable
        placeholder="所属门店"
        style="width: 220px"
        @change="handleStoreChange"
      >
        <el-option
          v-for="item in storeList"
          :key="item.organizationId"
          :label="item.organizationName"
          :value="item.organizationId"
        />
      </el-select>
    </el-form-item>
  </div>
</template>

<script>
export default {
  name: 'OrganizationSelector',
  props: {
    // 接收父组件传入的查询参数对象，使用 .sync 或 v-model
    value: {
      type: Object,
      default: () => ({
        headquartersId: null,
        chainId: null,
        storeId: null
      })
    },
    // 用户组织类型，用于控制连锁的显示
    userType: {
      type: [String, Number],
      default: 5 // 默认门店类型
    },
    // 是否需要加载总部/连锁/门店列表（在父组件 created 时已加载的情况下可设置为 false）
    loadInitialData: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      internalValue: {
        headquartersId: this.value.headquartersId,
        chainId: this.value.chainId,
        storeId: this.value.storeId
      },
      headquartersList: [], // 总部列表
      chainList: [],        // 连锁列表
      storeList: []         // 门店列表
    };
  },
  watch: {
    // 监听 prop value 变化，更新 internalValue
    value: {
      handler(newVal) {
        this.internalValue = { ...newVal };
      },
      deep: true
    },
    // 监听 internalValue 变化，通过 $emit 向上同步
    internalValue: {
      handler(newVal) {
        this.$emit('input', newVal); // 使用 v-model
        this.$emit('change', newVal); // 额外的 change 事件
      },
      deep: true
    }
  },
  created() {
    if (this.loadInitialData) {
      this.initOrganizationList();
    }
  },
  methods: {
    /**
     * @description 模拟获取组织机构列表的API请求
     * @param {number} type 组织类型：5-店铺, 4-连锁, 1-总部
     * @param {string} parentId 父级ID（查询门店时传入连锁ID，查询连锁时传入总部ID）
     * @returns {Promise}
     */
    getOrganizationListApi(type, parentId = '') {
      let map = {
        organizationType: type,
        page: 1,
        pageSize: 1000
      };
      if (parentId) {
        map.parentId = parentId;
      }
      // **注意：这里假设 $api.getOrganizationList 接口是可用的**
      // 如果 $api 未全局可用，需要在此处引入或通过 prop/inject 获取
      return this.$api.getOrganizationList(map);
    },

    // 初始化加载总部/连锁/门店列表
    initOrganizationList() {
      const type = this.userType;
      // organizationType，5是店铺，4是连锁，1是总部
      if (type == 5) {
        // 如果是门店管理员，直接加载门店列表
        this.getOrganizationListApi(5).then(res => {
          this.storeList = res.list.map(item => ({
            ...item,
            organizationId: item.organizationId || item.value
          })); // 统一 organizationId
        });
      } else if (type == 4) {
        // 如果是连锁管理员，直接加载连锁列表，并在连锁变化时加载门店
        this.getOrganizationListApi(4).then(res => {
          this.chainList = res.list.map(item => ({
            ...item,
            organizationId: item.chainOrganizationId || item.organizationId
          })); // 统一 organizationId
          // 如果默认有选中连锁ID，加载门店
          if(this.internalValue.chainId) {
            this.loadStoreList(this.internalValue.chainId);
          }
        });
      } else if (type == 1) {
        // 如果是总部管理员，加载总部列表，并在总部变化时加载连锁
        this.getOrganizationListApi(1).then(res => {
          this.headquartersList = res.list.map(item => ({
            ...item,
            organizationId: item.headquartersId || item.organizationId
          })); // 统一 organizationId
          // 如果默认有选中总部ID，加载连锁
          if(this.internalValue.headquartersId) {
            this.loadChainList(this.internalValue.headquartersId);
          }
        });
      }
    },

    // 加载连锁列表
    loadChainList(headquartersId) {
      this.chainList = [];
      this.internalValue.chainId = null;
      this.storeList = [];
      this.internalValue.storeId = null;

      if (headquartersId) {
        this.getOrganizationListApi(4, headquartersId).then(res => {
          this.chainList = res.list.map(item => ({
            ...item,
            organizationId: item.chainOrganizationId || item.organizationId
          }));
        });
      }
    },

    // 加载门店列表
    loadStoreList(chainId) {
      this.storeList = [];
      this.internalValue.storeId = null;

      if (chainId) {
        this.getOrganizationListApi(5, chainId).then(res => {
          this.storeList = res.list.map(item => ({
            ...item,
            organizationId: item.organizationId
          }));
        });
      }
    },

    // 总部切换处理
    handleHeadquartersChange(value) {
      // 切换总部时，清空连锁和门店
      this.internalValue.chainId = null;
      this.internalValue.storeId = null;
      this.loadChainList(value);
    },

    // 连锁切换处理 (原 onChainChange)
    handleChainChange(value) {
      // 切换连锁时，清空门店
      this.internalValue.storeId = null;
      this.loadStoreList(value);
    },

    // 门店切换处理
    handleStoreChange(value) {
      // 门店切换后不需要额外的逻辑
    },

    // 外部调用：重置选择器
    reset() {
      this.internalValue.headquartersId = null;
      this.internalValue.chainId = null;
      this.internalValue.storeId = null;
      this.chainList = [];
      this.storeList = [];
      if (this.loadInitialData) {
        this.initOrganizationList(); // 重新加载初始数据
      }
    }
  }
};
</script>

<style scoped>
.organization-selector {
  display: contents; /* 使 el-form-item 保持在一行 */
}
</style>
